package cn.sc.summer.redis.util;

import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.http.HttpRequest;
import cn.sc.summer.constant.util.AssertUtil;
import com.alibaba.cloud.nacos.NacosConfigProperties;
import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * 类名：nacos的api请求
 *
 * @author a-xin
 * @date 2024/5/22 17:16
 */
@Slf4j
@Component
public class NacosService {

    /**
     * 获取nacos登录token
     *
     * @param nacosDiscoveryProperties nacos配置文件
     * @return token信息
     */
    public static String getAccessToken(@NonNull NacosDiscoveryProperties nacosDiscoveryProperties) {
        return getAccessToken(nacosDiscoveryProperties.getServerAddr(), nacosDiscoveryProperties.getUsername(), nacosDiscoveryProperties.getPassword());
    }

    /**
     * 获取nacos登录token
     *
     * @param serverAddr nacos地址
     * @param username   用户名
     * @param password   密码
     * @return token信息
     */
    public static String getAccessToken(@NonNull String serverAddr, @NonNull String username, @NonNull String password) {
        final String DEFAULT_TOKEN = "AUTH_DISABLED";
        return AssertUtil.functionIf(CharSequenceUtil.isNotBlank(username) && CharSequenceUtil.isNotBlank(password), () -> {
            String loginUrl = "http://" + serverAddr + "/nacos/v1/auth/users/login";
            Map<String, Object> loginParams = new HashMap<>();
            loginParams.put("username", username);
            loginParams.put("password", password);
            String loginResult = HttpRequest.post(loginUrl).form(loginParams).execute().body();
            try {
                JSONObject jsonObject = JSONObject.parseObject(loginResult);
                if (jsonObject.containsKey("accessToken")) {
                    String accessToken = (String) jsonObject.get("accessToken");
                    if (CharSequenceUtil.isBlank(accessToken) || accessToken.equals(DEFAULT_TOKEN)) {
                        return DEFAULT_TOKEN;
                    }
                    return accessToken;
                }
                return DEFAULT_TOKEN;
            } catch (Exception ignored) {
                return DEFAULT_TOKEN;
            }
        }, DEFAULT_TOKEN);
    }

    /**
     * 创建nacos配置文件服务
     *
     * @param nacosConfigProperties nacos配置信息
     * @return 配置文件服务
     * @throws NacosException 创建异常
     */
    public static ConfigService getConfigService(@NonNull NacosConfigProperties nacosConfigProperties) throws NacosException {
        return getConfigService(nacosConfigProperties.getServerAddr(),
                nacosConfigProperties.getNamespace(),
                nacosConfigProperties.getUsername(),
                nacosConfigProperties.getPassword());
    }

    /**
     * 创建nacos配置文件服务
     *
     * @param address   nacos地址
     * @param namespace 命名空间
     * @param username  用户名
     * @param password  登录密码
     * @return 配置文件服务
     * @throws NacosException 创建异常
     */
    public static ConfigService getConfigService(String address, String namespace, String username, String password) throws NacosException {
        Properties properties = new Properties();
        properties.put(PropertyKeyConst.SERVER_ADDR, address);
        properties.put(PropertyKeyConst.NAMESPACE, namespace);
        properties.put(PropertyKeyConst.USERNAME, username);
        properties.put(PropertyKeyConst.PASSWORD, password);
        return NacosFactory.createConfigService(properties);
    }

    /**
     * 创建nacos配置文件服务
     *
     * @param nacosConfigProperties nacos配置信息
     * @return 配置文件服务
     * @throws NacosException 创建异常
     */
    public static NamingService getNamingService(@NonNull NacosDiscoveryProperties nacosConfigProperties) throws NacosException {
        return getNamingService(nacosConfigProperties.getServerAddr(),
                nacosConfigProperties.getNamespace(),
                nacosConfigProperties.getUsername(),
                nacosConfigProperties.getPassword());
    }

    /**
     * 创建nacos实例服务
     *
     * @param address   nacos地址
     * @param namespace 命名空间
     * @param username  用户名
     * @param password  登录密码
     * @return 配置文件服务
     * @throws NacosException 创建异常
     */
    public static NamingService getNamingService(String address, String namespace, String username, String password) throws NacosException {
        Properties properties = new Properties();
        properties.put(PropertyKeyConst.SERVER_ADDR, address);
        properties.put(PropertyKeyConst.NAMESPACE, namespace);
        properties.put(PropertyKeyConst.USERNAME, username);
        properties.put(PropertyKeyConst.PASSWORD, password);
        return NacosFactory.createNamingService(properties);
    }

}
